package com.zdw.demo.config.pay;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.net.URLDecoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.nio.charset.Charset;
import java.util.Date;

@Service
@Slf4j
public class ReqDecryption {

    /**
     * xor加密解密
     *
     * @param str
     * @param key
     * @return
     */
    public static String xorDecrypt(String str, String key) {
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            int charCode = str.charAt(i) ^ key.charAt(i % key.length());
            result.append((char) charCode);
        }
        return result.toString();
    }

    /**
     * 验证请求是否合法
     *
     * @param secretKey
     * @return
     */
    public static String getReqUserId(String secretKey, String deKey) {
        try {
            String   deCode64    = Base64.decodeStr(secretKey);
            String   deCodeUtf8  = URLDecoder.decode(deCode64, Charset.forName("UTF-8"));
            String   plaintext   = xorDecrypt(deCodeUtf8, deKey);
            String[] aryPlantext = plaintext.split(",");
            if (aryPlantext.length != 2) {
                log.error("解密失败1: 结构不对");
                return null;
            }
            if (Math.abs(DateUtil.betweenMs(DateUtil.parse(aryPlantext[1], "yyyyMMddHHmmss"), new Date())) > 1000 * 120) {
                log.error("解密失败2: 请求过期");
                return null;
            }
            return aryPlantext[0];
        } catch (Exception e) {
            log.error("getReqUserId异常", e);
            return null;
        }
    }


}
